/*
* api层
* 
* 验证api
* 
* */

'use strict';

const jwt = require('jsonwebtoken');
const fs = require('fs');

//const mongo = require('./mongo');

var Url = require('url');
var util = require('./util');
var process = require('process');

const cert = fs.readFileSync('./private.key');	// 加密私钥
var auth = {};

// 登录验证
auth.login = function(req, res) {

	console.log('login');

	var username = req.body.username,
		password = req.body.password;

	if(!username || !password){
		return res.sendStatus(401);
	}

	//mongo.login(username, password, res);
};

// 对需要token的api调用进行token 时间戳 sign验证
auth.verifyToken = function(req, res, next) {
	var verifyparm = req.headers['token'] || req.headers['xtime']||req.headers['sign'];
	if(verifyparm){ //验证是否缺失该参数

		var timestamp = req.headers['xtime'];

		if (process.uptime() - timestamp >1000*60*15){

			// 过期
			return res.sendStatus(403);
		}

		try{
			var userinfo = jwt.verify(token, cert);
			req._tokendata = userinfo;
			next();
		}catch(err){
			console.log(err);
			return res.sendStatus(401);
		}
	}else{
		return res.sendStatus(403);
	}
};

auth.logon = function(req, res) {

	console.log('logon');

	var username = req.body.username,
		password = req.body.password;

	if(!username || !password){
		return res.sendStatus(401);
	}

	//mongo.logon(username,password, res);

}

auth.verifyApi = function(req, res, next) {

}

auth.queryurl = function(req, res){

	//var url_parts = Url.parse(req.url, true);
    //
	//var query = url_parts.query;
	var json = JSON.stringify(req.query);



	console.log('query '+JSON.stringify(req.query))
}

 function sign (json) {
	 var bool = true;

	 var temp ='';
	 for (var key in json) {

		 if (bool == true){
			 bool = false;
		 }else {
			 temp+='&';
		 }

		 temp += key +'=';

		 if(json[key]) {
			 temp+= json[key];
		 }
	 }

	 return util.MD5(temp);
}

module.exports = auth;